package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.CategoryDTO;
import com.lastproject.ejb.entities.Category;
import com.lastproject.ejb.util.CategoryConversion;

/**
 * Session Bean implementation class CategoryDAO author : Zier Erik
 */
@Stateless
public class CategoryDAO implements CategoryDAORemote {

	@PersistenceContext
	private EntityManager em;
	@EJB
	CategoryConversion conv;

	public CategoryDAO() {
	}

	@Override
	public void create(CategoryDTO entity) {
		em.persist(conv.fromDTO(entity));
		em.flush();
	}

	@Override
	public void edit(CategoryDTO entity) {
		em.merge(conv.fromDTO(entity));
	}

	@Override
	public void remove(CategoryDTO entity) {
		Category category = em.find(Category.class, conv.fromDTO(entity)
				.getId());
		em.remove(category);
	}

	@Override
	public CategoryDTO findById(Object id) {
		Category category = em.find(Category.class, id);
		return conv.fromEntity(category);
	}

	@Override
	public List<CategoryDTO> findAll() {

		List<Category> categorys = em.createNamedQuery("Category.findAll",
				Category.class).getResultList();

		List<CategoryDTO> categorydtolist = new ArrayList<CategoryDTO>();

		for (Category category : categorys) {

			CategoryDTO cDto = new CategoryDTO();
			cDto = conv.fromEntity(category);
			categorydtolist.add(cDto);
		}

		return categorydtolist;
	}

	@Override
	public CategoryDTO findByName(String category) {
		return conv.fromEntity(em
				.createNamedQuery("Category.findByName", Category.class)
				.setParameter("nameParam", category).getResultList().get(0));
	}

}
